package com.unswift.window.listener;

import java.awt.Component;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

import javax.swing.JTextField;

import com.unswift.constant.ActionConstant;
import com.unswift.utils.NumberUtils;
import com.unswift.utils.ObjectUtils;

public class InputKeyListener extends KeyAdapter implements ActionConstant{

	private String action;
	private Component[] comps;
	
	public InputKeyListener(String action, Component...comps) {
		this.action=action;
		this.comps=comps;
	}
	
	@Override
	public void keyReleased(KeyEvent e) {
		if(ActionConstant.ACTION_PROJECT_NAME.equals(action)){
			JTextField input = (JTextField)e.getComponent();
			String text=input.getText();
			JTextField projectPath = (JTextField)comps[0];
			JTextField projectDomain = (JTextField)comps[1];
			String path=projectPath.getText();
			if(ObjectUtils.isEmpty(text)){
				int index=path.lastIndexOf('\\');
				if(index!=-1){
					projectPath.setText(path.substring(0, index+1));
				}else{
					index=path.lastIndexOf('/');
					if(index!=-1){
						projectPath.setText(path.substring(0, index+1));
					}
				}
				projectDomain.setText("");
			}else{
				int index=path.lastIndexOf('\\');
				if(index!=-1){
					projectPath.setText(path.substring(0, index+1)+text);
				}else{
					index=path.lastIndexOf('/');
					if(index!=-1){
						projectPath.setText(path.substring(0, index+1)+text);
					}
				}
				String domain=text.replace("-", ".");
				domain="com."+domain;
				if(!domain.contains(".cloud")){
					domain+=".cloud";
				}
				projectDomain.setText(domain);
			}
		}else if(ActionConstant.ACTION_SERVER_FILE_NAME.equals(action)){
			JTextField input = (JTextField)e.getComponent();
			String text=input.getText();
			if(ObjectUtils.isNotEmpty(text)){
				String[] keywords=text.split("\\-");
				if(keywords.length==3){
					JTextField serverName=(JTextField)comps[0];
					JTextField serverPort=(JTextField)comps[1];
					serverName.setText(keywords[2]);
					if(NumberUtils.isNumber(keywords[1], false)){
						serverPort.setText("8"+keywords[1]);
					}
				}
			}
		}
	}
	
	public Component[] getComps() {
		return comps;
	}
}
